#!C:\python25\python.exe

import xml2html
import cgi
import ConfigParser
import string, os, sys
from time import strftime
import result_parser
import string
import conn

cfg = ConfigParser.ConfigParser()
cfg.read("path.cfg")
templatepath = cfg.get("template", "path")
reportpath = cfg.get("report", "path")
resultpath = cfg.get("result", "path")
form = cgi.FieldStorage()

def template2output(templatefilename, events, final_result = None, np = None):
   template = str(form.getvalue("template"))
   mrn = form.getvalue("MRN") 
   if mrn is None:
      bedno = str("Bed " + str(form.getvalue("bedno"))).strip()
      query = "select cfgpatients.medrecnum from cfgpatients, bedconfig, ptvisit where cfgpatients.gprid = ptvisit.prid and \
ptvisit.inbed_cid = bedconfig.cid and ptvisit.inbed_oid = bedconfig.oid and bedconfig.name_ IN ('"+bedno+"')"
      print query
      mrn = conn.toGICU(query)
      mrn = mrn[0]
                   
   output = str(form.getvalue("outputtype"))
   
   time = strftime("%Y-%m-%d-%H-%M-%S")
   resultfilename = resultpath + template + "_" + mrn + "_"+ time + ".xml"
   result_parser_object = result_parser.result_parser(templatefilename,resultfilename, events, final_result,np)
   
   if output == "Browser":
      xml2html_object = xml2html.xml2html(resultfilename)
   elif output == "HtmlFile":
      print "Content-Type: text/html\n\n" 
      time = strftime("%Y-%m-%d-%H-%M-%S")
      reportfilename = reportpath + template + "_" + mrn + "_"+ time + ".html"
      xml2html_object = xml2html.xml2html(resultfilename,reportfilename)
      print "<BR><B>Report has been saved into "+ reportfilename + "</B>"
   else:
      print "Content-Type: text/html\n\n" 
      print "<BR><B>Report has been saved into "+ resultfilename + "</B>"

   
def xml2output():
   result = str(form.getvalue("result"))
   output = str(form.getvalue("outputtype"))
   resultfilename = resultpath + result + ".xml"
   
   if output == "Browser":
      xml2html_object = xml2html.xml2html(resultfilename)
   else:
      print "Content-Type: text/html\n\n" 
      reportfilename = reportpath + result + ".html"
      xml2html_object = xml2html.xml2html(resultfilename,reportfilename)
      print "<BR><B>Report has been saved into "+ reportfilename + "</B>"      
